<template>
  <div id="login">
    <img class="logo" alt="头像" src="@/assets/logo.png">
    <div class="user-info" v-if="isLogin">
      <span>{{userInfo.name}}</span>
    </div>
    <div class="entry" v-else>
      <el-button type="primary" @click="loginOpen">登 录</el-button>
      <el-button type="">退 出</el-button>
    </div>
    <el-dialog title="登 录" :visible.sync="loginVisible" width="30%" :before-close="handleClose">
      <el-form label-width="80px" :model="formLogin" :rules="rules" ref="ruleForm" >
        <el-form-item label="用户名：" prop="name">
          <el-input v-model="formLogin.name"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="formLogin.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="login">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { UserInfo } from '@/types/index.ts'
import { setToken } from '@/utils/common'
@Component
export default class Login extends Vue {
  private isLogin: boolean = false
  private loginVisible: boolean = false
  private userInfo: UserInfo = {
    name: ''
  }
  private formLogin: any = {
    name: '',
    password: ''
  }
  private rules: any = {
    name: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' }
    ],
  }
  private handleClose(done: any) {
    this.$confirm('确认关闭？').then((res) => {
      done();
      this.$refs.ruleForm.resetFields();
    }).catch((err) => {
      //
    });
  }
  private loginOpen() {
    this.loginVisible = true
  }
  private login() {
     this.$refs.ruleForm.validate((valid: any) => {
      if (valid) {
        setToken('111')
        let data  = JSON.stringify(this.formLogin)
        window.sessionStorage.setItem('userInfo', data)
        this.loginVisible = false
        this.isLogin = true
        history.go(0)
      } else {
        return false;
      }
    })
  }

}
</script>

<style lang="stylus" scoped>
#login
  padding 10px 30px
  height 40px
  display flex
  justify-content space-between
  border-bottom 1px solid #e6e6e6
&.logo
  width 30px
  border-radius 50%
  margin auto 0
  margin-left 10px
&.entry
  margin auto 0
  margin-right 10px
</style>
